package com.xiaoluo.web.k8;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoluo.service.KubernetesService;
import com.xiaoluo.service.ServerService;
import com.xiaoluo.web.BaseController;
import com.xiaoluo.web.form.ResultForm;
import io.fabric8.kubernetes.api.model.*;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * Project : SpiderManager
 * Package : com.xiaoluo.web
 * Created by Willian.
 * Date  : 2015/10/21 20:29.
 */
@Controller
@RequestMapping("/pod")
public class PodController extends BaseController {
    private final static Logger logger = LoggerFactory.getLogger(PodController.class);
    private ObjectMapper mapper = new ObjectMapper();
    @Autowired
    private ServerService serverService;
    @Autowired
    private KubernetesService kubernetesService;

    @RequestMapping(value = "/getPod",method = RequestMethod.GET)
    @ResponseBody
    public ResultForm getPod(ModelMap model,String namespace,String name){

        ResultForm result = new ResultForm(0,"sucessed");

        if(name !=null && !"".equals(name)){
            Pod pod = kubernetesService.getClient().pods().inNamespace(namespace).withName(name).get();
            result.setData(pod);
        }

        return result;
    }

    @RequestMapping(value = "/viewPod",method = RequestMethod.GET)
    public  String viewPod(ModelMap model,String namespace,String name){

        if(name !=null && !"".equals(name)){
            Pod pod = kubernetesService.getClient().pods().inNamespace(namespace).withName(name).get();
            model.addAttribute("pod",pod);
        }

        model.addAttribute("nodes",kubernetesService.getClient().nodes().list());
        model.addAttribute("namespaces",kubernetesService.getClient().namespaces().list());
        return "k8/pod/editPod";
    }
    @RequestMapping(value = "/savePod",produces = "application/json; charset=UTF-8")
    @ResponseBody
    public  ResultForm savePod(ModelMap model,@RequestBody String params){
        logger.info("User:{},save pod:{}",getCurrentUser().getUserName(),params);

        ResultForm result = new ResultForm(0,"success");

        try {
            Pod pod = mapper.readValue(params, Pod.class);
            kubernetesService.getClient().pods().delete(pod);
            kubernetesService.getClient().pods().create(pod);
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*
        EditablePod  pb = new PodBuilder()
                .withNewMetadata()
                    .withName(name).withNamespace(namespace)
                    .withUid(UUID.randomUUID().toString()).withSelfLink(UUID.randomUUID().toString())
                .endMetadata()
                .withNewSpec()
                    .withNodeName(node).withDnsPolicy(dnsPolicy)
                    .withContainers()
                        .addNewContainer()
                        .withName(container)
                        .withImage(image)
                        .withTerminationMessagePath("/dev/termination-log")
                        .withImagePullPolicy(pullPolicy)
                        .withPorts()
                            .addNewPort()
                            .withProtocol(protocol)
                            .withHostPort(hostPort)
                            .withContainerPort(containerPort)
                        .endPort()
                    .endContainer()
                .endSpec()
                .withNewStatus()
                    .withPhase(phase)
                .endStatus().build();

        kubernetesClient.pods().create(pb);
        */
        return result;
    }
    @RequestMapping(value = "/viewContainer",method = RequestMethod.GET)
    @ResponseBody
    public ResultForm viewContainer(ModelMap model,String namespace,String name){

        ResultForm result = new ResultForm(0,"sucessed");

        if(name !=null && !"".equals(name)){
            Pod pod = kubernetesService.getClient().pods().inNamespace(namespace).withName(name).get();
            if(pod != null){
                result.setData(pod.getSpec().getContainers());
            }
        }
        return result;
    }

    @RequestMapping(value = "/delPod",method = RequestMethod.GET)
    public  String delPod(ModelMap model,String namespace,String name){
        logger.info("User:{},del pod:{} - {}",getCurrentUser().getUserName(),name,namespace);
        EditablePod  pb = new PodBuilder().withNewMetadata()
                                            .withName(name).withNamespace(namespace)
                                            .endMetadata().build();
        kubernetesService.getClient().pods().delete(pb);

        return "forward:/k8/";
    }


}
